package my.util.single;

import my.util.AbstractList;

/**
 * <p>
 * 单链表
 * </p>
 *
 * @author AJun
 * @since 2020/8/12
 */
public class SingleLinkedList<E> extends AbstractList<E> {

    /**
     * 头节点
     */
    private Node<E> first;

    /**
     * 节点
     */
    private static class Node<E> {
        E element; // 节点数据
        Node<E> next; // 指向下一个节点

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public int indexOf(E element) {
        Node<E> node = first;
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (node.element == null)
                    return i;
                node = node.next;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (element.equals(node.element))
                    return i;
                node = node.next;
            }
        }
        return -1;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E old = node.element;
        node.element = element;
        return old;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        if (index == 0) { // 添加到最前面(头插)
            first = new Node<>(element, first); // 注意理解这里，要将 first 引用指向新加的头节点上
        } else { // 任意位置添加
            Node<E> prev = node(index - 1);
            prev.next = new Node<>(element, prev.next);
        }
        size++; // 大小 +1
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);

        Node<E> node = first;
        if (index == 0) {
            first = first.next;
        } else {
            Node<E> prev = node(index - 1);
            node = prev.next;
            prev.next = node.next;
        }
        size--;
        return node.element;
    }

    @Override
    public void clean() {
        size = 0;
        first = null;
    }

    /**
     * 根据传入的索引返回该索引的元素
     */
    private Node<E> node(int index) {
        rangeCheck(index);

        Node<E> node = first;
        for (int i = 0; i < index; i++)
            node = node.next;
        return node;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("size=").append(size).append(", [");
        Node<E> node = first;
        for (int i = 0; i < size; i++) {
            if (i > 0) sb.append(", "); // 不需要减法运算
            sb.append(node.element);

            node = node.next;
        }
        sb.append("]");
        return sb.toString();
    }

}
